package com.otp.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.android.volley.request.StringRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.otp.Activity.CourseDetail;
import com.otp.Activity.DashBoard;
import com.otp.Activity.R;
import com.otp.adapter.CourseListAdapter;
import com.otp.model.Course;
import com.otp.model.CourseInfo;
import com.otp.util.Constants;
import com.otp.util.HttpUtil;
import com.otp.util.MyVolley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class VideoFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2,AdapterView.OnItemClickListener {

    private PullToRefreshListView listView = null;
    private List<Course> list = new ArrayList<Course>();
    private static final int GET_COURSE_INFO = 1;
    private static final int GET_COURSE_INFO_ERROR = 2;
    private CourseListAdapter courseListAdapter = null;
    private Handler handler;
    private boolean isPullToRefresh = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video, container, false);
        listView = (PullToRefreshListView) view.findViewById(R.id.videoList);



        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    getCourseData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT);
        View header = inflater.inflate(R.layout.slide_banner, listView, false);
        header.setLayoutParams(layoutParams);
        listView.getRefreshableView().addHeaderView(header);
        listView.getRefreshableView().setHeaderDividersEnabled(false);
        listView.getRefreshableView().setSelectionFromTop(2,2);
        courseListAdapter = new CourseListAdapter(this.getActivity().getApplicationContext(),list);
        handler= new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case GET_COURSE_INFO:
                        list = (List<Course>) msg.obj;
                        courseListAdapter.setList(list);
                        courseListAdapter.notifyDataSetChanged();
                        listView.onRefreshComplete();
                        break;
                    case GET_COURSE_INFO_ERROR:
                         showToast("与服务器连接失败，请重试!");
                        listView.onRefreshComplete();
                        ;break;
                }
            }
        };
        listView.setAdapter(courseListAdapter);
        //设置PullRefreshListView上提加载时的加载提示
        Course coursei = new Course();
        coursei.setCourseName("hehe");
        coursei.setCourseDescription("fahhfda");
        list.add(coursei);
        listView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");
        listView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
        listView.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多...");
        // 设置PullRefreshListView下拉加载时的加载提示
        listView.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        listView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新...");
        listView.getLoadingLayoutProxy(true, false).setReleaseLabel("松开刷新...");
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(this);
        listView.setOnItemClickListener(this);
        return view;
    }

    public void setAdapterToList(List<CourseInfo> list) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        try {
            isPullToRefresh = true;
            getCourseData();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this.getActivity(), CourseDetail.class);
        Course course = courseListAdapter.getItem(position - Constants.LISTVIEW_OFFSET);
        intent.putExtra(Constants.COURSE_ID,course.getId());
        intent.putExtra(Constants.COURSE_NAME,course.getCourseName());
        intent.putExtra(Constants.COURSE_VIDEO_PATH,course.getCourseVideo());
        this.startActivity(intent);
    }

    public void getCourseData() throws JSONException{
       // JSONObject jsonObject = new JSONObject();
        RequestQueue mRequestQueue = MyVolley.getRequestQueue();
        String url ;
        if (isPullToRefresh) {
            url = "Course/getAll?"+ Math.random();
        } else {
            url = "Course/getAll";
        }
        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, HttpUtil.getURL(url),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Message msg = new Message();
                        Gson gson = new Gson();
                        CourseInfo courseInfo = gson.fromJson(response,CourseInfo.class);
                        if (courseInfo.getStatus().equals(Constants.SUCCESS)) {
                            msg.obj = courseInfo.getCourseList();
                            msg.what = GET_COURSE_INFO;
                            handler.sendMessage(msg);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Message msg = new Message();
                        msg.what = GET_COURSE_INFO_ERROR;
                        handler.sendMessage(msg);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");
                return headers;
            }
        };
        mRequestQueue.add(jsonObjectRequest);
    }

    public void showToast(String msg){
        Toast.makeText(this.getActivity().getApplicationContext(),msg,Toast.LENGTH_LONG).show();
    }
}
